package com.macro.mall.portal.controller.klxx;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.dto.applet.AppletLoginMemberDTO;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dabaoqiang
 */
@Slf4j
@Api(tags = "小程序用户登录接口")
@RequestMapping(value = "/applet/user")
@RestController
public class AppletLoginController {

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Resource
    private UmsMemberService memberService;

    @Resource
    private WxMaService wxMaService;


    /**
     * 根据code获取访问微信小程序的微信用户信息
     *
     * @param code 微信CODE
     * @return
     */
    @ApiOperation(value = "根据code获取访问微信小程序的微信用户信息")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "appid", value = "微信appid", required = true, dataType = "String"), @ApiImplicitParam(paramType = "query", name = "code", value = "微信code", required = true, dataType = "String")})
    @GetMapping(value = "/weixin-login-ByCode")
    public CommonResult<WxMaJscode2SessionResult> getMaUserInfoByCode(String appid, String code) {
        if (!wxMaService.switchover(appid)) {
            Asserts.fail(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        if (StringUtils.isBlank(code)) {
            log.error("getMaUserInfoByCode error code is null");
            Asserts.fail("code不能为空");
        }
        try {
            //微信账号信息
            WxMaJscode2SessionResult wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
            return CommonResult.success(wxMaJscode2SessionResult);
        } catch (WxErrorException e) {
            log.error("通过{}获取微信账户信息失败", code);
            return CommonResult.failed("获取微信账户信息失败");
        }
    }

    @ApiOperation("微信登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@RequestBody AppletLoginMemberDTO req) {
        log.info("用户登录信息：{}", JSON.toJSONString(req));
        WxMaJscode2SessionResult wxResult = null;
        try {
            wxResult = wxMaService.jsCode2SessionInfo(req.getCode());
        } catch (WxErrorException e) {
            log.error("通过{}获取微信账户信息失败", req.getCode());
            return CommonResult.failed("获取微信账户信息失败");
        }
        if (null == wxResult) {
            return CommonResult.failed(String.format("通过[%s]获取微信账户信息失败！", req.getCode()));
        }
        // 获取用户
        UmsMember umsMember = memberService.selectHsMemberByOpenId(wxResult.getOpenid());
        if (umsMember == null) {
            memberService.saveMember(wxResult.getOpenid());
        }
        String token = memberService.wxLogin(wxResult.getOpenid());
        if (StringUtils.isEmpty(token)) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }


}
